<template>
	<!--  #ifndef H5 -->
	<view class="loginbox">
	<!-- #endif -->
	<!-- #ifdef H5 -->
	<view class="loginbox-h5" >
	<!-- #endif -->
		<u-navbar :border-bottom="false" title=" " :immersive="true" :custom-back="BackHome"
			:background="{backgroundColor: 'rgba(0, 0, 0, 0)'}">
			<!-- <view style="padding-right: 20rpx;" slot="right">
				帮助
			</view> -->
		</u-navbar>
		<view class="top">
			<!--  #ifndef H5 -->
			<view class="text">
				<view class="sys-title">{{appName}}</view>
				<view class="text-content">{{ $t("欢迎登录~快来领取您的专属好礼吧") }}</view>
			</view>
			<!-- #endif -->
			
			<!-- #ifdef APP-PLUS -->
			<view class="h5-biaodan">
				<view class="row">
					<u-field v-model="phone" type="number" label="+86" maxlength="11" placeholder="请填写手机号">
					</u-field>
				</view>
				
				<view class="row">
					<u-field v-model="num" type="number" label="验证码" placeholder="请输入验证码">
						<text class="huoqu" slot="right" @click="getCode">{{codeText}}</text>
					</u-field>
					<u-verification-code ref="uCode" @change="codeChange" change-text="xs"></u-verification-code>
				</view>
				<button class="h5-btn" @click="submit">{{ $t("登录") }}</button>
			</view>
			<!-- #endif -->
			
			<!-- #ifdef H5 -->
			<view class="h5-biaodan" v-if="showMpwei">
			  <view class="h5-biaodan-new">
				  <view class="h5-biaodan-new-img">
					  	<image  :src="tempavatarUrl" mode=""></image>
				  </view>
				   <view class="h5-biaodan-new-label">
					   为了您更好的线上抽盒/购物体验，，请您完成授权
				   </view>
				   <view class="h5-biaodan-new-btn"  @click="h5_wx_login">微信登录</view>
				   <view class="h5-biaodan-new-tip" @click="showMpwei = false">手机号临时登录</view>
			  </view>
			</view>
			<view class="h5-biaodan" v-if="!showMpwei">
				<view class="row">
					<u-field v-model="phone" type="number" label="+86" maxlength="11" placeholder="请填写手机号">
					</u-field>
				</view>
				
				<view class="row">
					<u-field v-model="num" type="number" label="验证码" placeholder="请输入验证码">
						<text class="huoqu" slot="right" @click="getCode">{{codeText}}</text>
					</u-field>
					<u-verification-code ref="uCode" @change="codeChange" change-text="xs"></u-verification-code>
				</view>
				<button class="h5-btn" @click="submit">{{ $t("登录") }}</button>
			</view>
			<!-- #endif -->
			<view class="biaodan">
			
				<!-- #ifdef MP-WEIXIN -->
				<view style="margin-bottom:20px;">
					<view class="row">
						<u-field v-model="phone" type="number" label="+86" maxlength="11" placeholder="请填写手机号"></u-field>
					</view>

					<view class="row">
						<u-field v-model="num" type="number" label="验证码" placeholder="请输入验证码">
							<text class="huoqu" slot="right" @click="getCode">{{codeText}}</text>
						</u-field>
						<u-verification-code ref="uCode" @change="codeChange" change-text="xs"></u-verification-code>
					</view>
					<button class="wexxin-view" @click="submit">{{ $t("登录") }}</button>
				</view>
				<view v-if="mp_login_type=='wx_login'">
					<view class="cell-info" style="margin-bottom: 20rpx;" v-if="share_ma">
						<text>{{ $t("邀请人为") }}</text>{{share_ma}}
					</view>

					<!-- <view class="wexxin-view" @click="weixin()">微信授权登录</view> -->
					<!-- <view class="wexxin-view"></view> -->
					<button open-type="getPhoneNumber" @getphonenumber="login" class="wexxin-view wexxin-view2">{{ $t("手机号快捷登录") }}</button>
				</view>
				<!-- #endif -->

			</view>

		</view>

		<!-- <view class="top">
			<image src="https://img.50api.cn/dingdang/qh.png" mode="widthFix"></image>
			<view class="text">
				<view>你好，</view>
				<view>欢迎来到{{appName}}</view>
			</view>
		</view> -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="mp-other">
			<!-- <text color="#999" @click="mp_login_type='mobile_login'" v-if="mp_login_type=='wx_login'">手机号码登录
			</text> -->
			<text color="#999" @click="mp_login_type='wx_login'" v-if="mp_login_type=='mobile_login'">{{ $t("微信快捷登录") }}
			</text>
		</view>
		<!-- #endif -->
		<!-- #ifdef APP-PLUS -->
		<!-- <view class="other-view">
			<text color="#999">其他登录方式</text>
			<image @click="applogin" src="../../../static/image/weixin.png" mode=""></image>
		</view> -->
		<!-- #endif -->
		<!-- #ifdef H5 -->
		<view class="other-view"  v-if="!showMpwei">
			<text>{{ $t("其他登录方式") }}</text>
			<!-- <image @click="h5_wx_login" src="../../../static/image/weixin.png" mode=""></image> -->
			<image @click="showMpwei = true" src="../../../static/image/weixin.png" mode=""></image>
		</view>
		<!-- #endif -->
		<view class="agree-box">
			<u-checkbox @change="checkboxChange" v-model="agreeChecked" shape="circle" style="position: relative;top:-15rpx">
			</u-checkbox>
			<view class="agree-box-text">
				{{ $t("若您的手机号未注册，将为你自动注册。注册或登录即表示已阅读并同意") }}
				<text class="book-style" @click="$.to('/pagesB/pages/my/agreement?type=user_agreement')">《{{ $t("用户协议") }}》</text>，
				<text class="book-style" @click="$.to('/pagesB/pages/my/agreement?type=privacy_policy')">《{{ $t("隐私协议") }}》</text>
			</view>
		</view>

		<u-popup mode="center" :popup="false" v-model="anShow" border-radius="20">
			<view class="popup-view">
				<view class="popup-view-title">{{ $t("您好，首次注册需要设置用户头像、昵称") }}</view>
				<view class="">
					<view class="cell-list">
						<text class="cell-list-left">{{ $t("用户头像") }}</text>
						<view class="cell-list-right right-pic">
							<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
								<image class="refreshIcon" :src="headImg" alt="点击上传头像"></image>
							</button>
						</view>

					</view>
					<view class="cell-list">
						<text class="cell-list-left">{{ $t("用户昵称") }}</text>
						<view class="cell-list-right">
							<input class="weui-input" type="nickname" v-model="nickName" placeholder="请输入昵称"
								@blur="bindblur" />
						</view>

					</view>
				</view>

				<view class="btn1">
					<view class="btn-sub" @click="saveUserInfo">{{ $t("保存用户信息") }}</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import config from "@/utils/config.js"
	export default {
		data() {
			return {
				phone: '', //手机号
				num: '', //验证码
				code: '',
				codeText: '',
				// nickName: '',
				headImage: '',
				share_ma: '',
				appName: '',
				pnoneNum: '',
				agreeChecked: false,
				avatarUrl: null,
				tempavatarUrl: '',
				nickname: '',
				mp_login_type: 'wx_login',
				h5_wx_openid: '',
				anShow: false,
				headImg: '',
				userToken : '',
				showMpwei : true
			}
		},
		onLoad(option) {
			let codeMa = uni.getStorageSync('share_ma')
			if (option.share_ma) {
				this.share_ma = option.share_ma
			}
			if (codeMa) {
				this.share_ma = codeMa
			}
			if (option.h5_wx_openid) {
				this.h5_wx_openid = option.h5_wx_openid;
				this.h5_wx_openid_login();
			}
			console.log(this.share_ma, "邀请码");
			this.getName()
			// console.log("baseUrl: " + JSON.stringify(config.baseUrl));
		},
		methods: {
			saveUserInfo() {
				if(!this.nickname){
						this.$tip.tip("请设置昵称")
						return
				}
				this.$http({
					url: "api/member/change_info",
					data: {
						"nickname": this.nickname,
						"image": this.headImg
					}
				}).then(result  => {
					if (result.data.code == 1) {
						setTimeout(() => {
							uni.showToast({
								title: '登录成功',
								icon: 'success',
								mask: true
							})
						}, 100)
					    let user = {...uni.getStorageSync('user') ,nickname : this.nickname , image : this.headImg }
						uni.setStorageSync('user', user)
						uni.$emit('updataUser');
						uni.switchTab({
							url: '/pages/tabBar/home'
						})
						
						// let user = uni.getStorageSync('user')
						// user = {...user , nickname : this.nickname , image : this.headImg }
						// uni.setStorageSync('user', user)
						// uni.setStorageSync('user_token', result.data.data.token)
						// uni.$emit('updataUser');
						// uni.switchTab({
						// 	url: '/pages/tabBar/home'
						// })
					}
				})
			},
			bindblur(e) {
				console.log('nickName', e)
				this.nickname = e.detail.value;
			},
			bindinput(e) {
				console.log('nickName', e)
				this.nickname = e.detail.value;
			},

			uploadImage(tempFilePaths) {
				console.log(uploadImage, '2222')
				let _this = this;
				uni.uploadFile({
					url: this.$baseUrl.baseUrl + 'api/upload/upload', //接口地址
					filePath: tempFilePaths,
					name: 'file',
					success: (res) => {
						let data = JSON.parse(res.data);
						if (data.code == 1) {
							console.log(data, '1222')
							// this.headImg = data.file
							// uni.hideLoading();
							// this.upData(data.file)
						} else {
							this.$tip.tip(data.msg)
						}
					}
				});
			},
			onChooseAvatar(res) {
				console.log("获取用户头像:" + JSON.stringify(res.detail.avatarUrl)),
					uni.uploadFile({
						url: this.$baseUrl.baseUrl + 'api/upload/upload', //接口地址
						filePath: res.detail.avatarUrl,
						name: 'file',

						success: (uploadFileRes) => {
							console.log("上传返回信息:" + JSON.stringify(uploadFileRes.data))
							let responseInfo = JSON.parse(uploadFileRes.data)
							if (responseInfo.code == 1) {
								this.avatarUrl = responseInfo.file
								this.headImg = responseInfo.file
								// console.log("图片上传地址:" + this.userImg)
							} else {
								uni.showToast({
									title: "图片上传失败,请重试!",
									duration: 3000
								})
							}

						}
					});
			},

			checkboxChange() {
				this.agreeChecked = !this.agreeChecked;
			},
			BackHome() {
				console.log('leftClick');
				uni.switchTab({
					url: '/pages/tabBar/home'
				});
			},
			applogin() {
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: (event) => {
						const {
							code
						} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						this.$http({
							url: "api/login/get_wechat_info_by_app",
							data: {
								"code": event.code
							}
						}).then(result => {
							console.log(result, '1111');
							if (result.data.code == 1) {
								uni.setStorageSync('user', result.data.data)
								this.getUser()
							}
						}).catch(err => {});
					},
					fail: (err) => {
						this.$tip.tip("授权失败")
						// 登录授权失败  
						// err.code是错误码
					}
				})
			},
			h5_wx_login() {
				if(!this.agreeChecked){
				      return this.$tip.tip("请确认阅读并同意用户与隐私协议")
				}
				var login_url = config.baseUrl + '/api/login/h5_wx_login';
				// alert(login_url);
				const system = uni.getSystemInfoSync()
				if (system.platform == 'ios') {
					window.location.href = login_url
				} else {
					window.open(login_url)
				}
			},
			h5_wx_openid_login() {
				this.$http({
					url: "api/login/h5_wx_login",
					data: {
						openid: this.h5_wx_openid,
						share_ma: this.share_ma,
					}
				}).then(res => {
					console.log(res);
					if (res.data.code == 1) {
						uni.setStorageSync('user_token', res.data.data.token)
						uni.setStorageSync('user', res.data.data.member_data)
						uni.$emit('updataUser');
						uni.switchTab({
							url: '/pages/tabBar/home'
						})
					} else {
						alert(JSON.stringify(res.data.msg));
						this.$tip.tip(res.data.msg)
					}
				}).catch(err => {});
			},
			login(e) {
				// if (!this.nickname) {
				// 	this.$tip.tip("请设置昵称")
				// 	return
				// }
				// this.weixin();
				// return;
				if (this.agreeChecked==false) {
					this.$tip.tip("请先同意用户协议和隐私协议")
					return;
				}
				if (e.detail.encryptedData) {
					let {
						code,
						encryptedData,
						iv
					} = e.detail
					this.$http({
						url: "api/login/get_mp_wechat_phone",
						data: {
							"code": code,
						}
					}).then(result => {
						if (result.data.code == 1) {
							this.pnoneNum = result.data.data.phoneNumber
							this.weixin()
						}
					}).catch(err => {});
				} else {
					// this.weixin()
					this.$tip.tip("授权失败")
				}
			},

			codeChange(text) {
				this.codeText = text;
			},
			weixin() {
				// if (!this.nickname) {
				// 	this.$tip.tip("请设置昵称")
				// 	return
				// }
				if (!this.agreeChecked) {
					this.$tip.tip("请先同意用户协议和隐私协议")
					return
				}
				uni.login({
					success: (request) => {
						if (request.code) {
							this.$http({
								url: "api/login/mp_wechat_login",
								data: {
									username: this.nickname,
									mobile: this.pnoneNum,
									image: this.avatarUrl || this.tempavatarUrl,
									"code": request.code,
									"nickName": this.nickname,
									"share_ma": this.share_ma,
								}
							}).then(result => {
								if (result.data.code == 1) {
									let user = result.data.data.member_data
									// let userToken = result.data.data.token
									// uni.setStorageSync('user_token', result.data.data.token)
									uni.setStorageSync('user_token', result.data.data.token)
									if(user && user.nickname){
										uni.setStorageSync('user', user)
										uni.$emit('updataUser');
										uni.switchTab({
											url: '/pages/tabBar/home'
										})
										// this.anShow = true
									}else{
										this.anShow = true
									}
								
								} else {
									this.$tip.tip(result.data.msg)
								}
							}).catch(err => {});
						}
					}
				})
			},
			getName() {
				this.$http({
					url: "/api/common/get_general",
				}).then(res => {
					if (res.data.code == 1) {
						this.appName = res.data.data.app_name
						this.tempavatarUrl = res.data.data.app_logo
						this.headImg = res.data.data.app_logo
					}
				}).catch(err => {});
			},
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					if (this.$tip.phoneReg.test(this.phone) == false) {
						this.$tip.tip('请填写正确的手机号')
						return
					}
					if (!this.agreeChecked) {
						this.$tip.tip("请先同意用户协议和隐私协议")
						return
					}
					// 模拟向后端请求验证码
					uni.showLoading({
						title: '正在获取验证码'
					})
					this.$http({
						url: "api/login/send_sms",
						data: {
							event: 'login',
							mobile: this.phone
						}
					}).then(res => {
						if (res.data.code == 1) {
							uni.hideLoading();
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						} else {
							this.$tip.tip(res.data.msg)
						}
					}).catch(err => {});
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			submit() {
				if (!this.agreeChecked) {
					this.$tip.tip("请先同意用户协议和隐私协议")
					return
				}
				if (this.$tip.phoneReg.test(this.phone) == false) {
					this.$tip.tip('请填写正确的手机号')
					return
				}
				if (this.num == '') {
					this.$tip.tip('请填写验证码')
					return
				}
				this.$http({
					url: "api/login/mobile_login",
					data: {
						mobile: this.phone,
						captcha: this.num,
						share_ma: this.share_ma,
					}
				}).then(res => {
					console.log(res);
					if (res.data.code == 1) {
						uni.setStorageSync('user_token', res.data.data.token)
						uni.setStorageSync('user', res.data.data.member_data)
						uni.$emit('updataUser');
						uni.switchTab({
							url: '/pages/tabBar/home'
						})
					} else {
						this.$tip.tip(res.data.msg)
					}
				}).catch(err => {});
			},
		}
	}
</script>

<style lang="scss">
	// .top {
	// 	position: relative;
	// }

	// .top image {
	// 	width: 750rpx;
	// }

	// .top .text {
	// 	position: absolute;
	// 	left: 60rpx;
	// 	top: 170rpx;
	// 	font-size: 50rpx;
	// }
	.top {
		position: absolute;
		top: 300rpx;

		.sys-title {
			font-size: 70rpx;
			font-weight: bold;
			color: #3643bd;
			padding-left: 50rpx;
		}

		.text-content {
			font-size: 30rpx;
			font-weight: bolder;
			color: #3643bd;
			padding-left: 50rpx;
			margin-top: 40rpx;
		}

		.biaodan {
			margin-top: 300rpx;
			width: 650rpx;
			margin-left: 50rpx;

			.wexxin-view {
				height: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #3643bd;
				color: #fff;
				font-size: 32rpx;
				// margin-left: 50rpx;
				border-radius: 30rpx;
			}
			.wexxin-view2 {
				background-color: #f75444;
			}

			.h5-btn {
				height: 100rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background-color: #3643bd;
				color: #fff;
				font-size: 32rpx;
				border-radius: 30rpx;
			}

		}
	}


	  
  .h5-biaodan{
	  width: 650rpx;
	  margin-left: 50rpx;
	  margin-top: 100rpx;
	  .h5-btn {
	  	height: 100rpx;
	  	display: flex;
	  	justify-content: center;
	  	align-items: center;
	  	background-color: #3643bd;
	  	color: #fff;
	  	font-size: 32rpx;
	  	border-radius: 30rpx;
	  }
  }


	// .biaodan {
	// 	padding: 40rpx 60rpx;
	// 	box-sizing: border-box;
	// }

	.huoqu {
		color: #3643bd;
	}

	.row {
		margin-bottom: 30rpx;
	}

	// .btn {
	// 	background-color: #00DAD9;
	// 	font-size: 32rpx;
	// 	margin-top: 40rpx;
	// }

	.loginbox {
		width: 100%;
		height: 100vh;
		background-image: url("https://img.50api.cn/vx.tongbayun.v3/loginbg.jpg");
		background-size: 100% 100%;
		position: relative;
	}
	
	.loginbox-h5{
		background-image: ''
	}
	// .other {
	// 	position: absolute;
	// 	width: 750rpx;
	// 	left: 0;
	// 	bottom: 100rpx;
	// 	text-align: center;
	// }




	.mp-other {
		position: absolute;
		bottom: 200rpx;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		text {
			font-size: 22rpx;
			color: #999;
		}
	}

	.other-view {
		position: absolute;
		bottom: 200rpx;
		width: 100%;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;

		text {
			font-size: 22rpx;
			color: #999;
		}

		image {
			width: 80rpx;
			height: 80rpx;
			margin-top: 30rpx;
		}
	}


	.agree-box {
		position: absolute;
		bottom: 100rpx;
		width: 650rpx;
		margin-left: 50rpx;
		display: flex;

		.agree-box-text {
			color: #222;
			font-size: 24rpx;
			line-height: 36rpx;
		}

		.book-style {
			color: #3643bd;
			font-size: 24rpx;
			line-height: 36rpx;

		}
	}

	// .agree-box {
	// 	width: 80vw;
	// 	margin-top: 100rpx;
	// 	box-sizing: border-box;
	// 	margin-left: 10vw;
	// 	display: flex;
	// }

	// .agree-box-text {
	// 	color: #999999;
	// 	font-size: 24rpx;
	// 	line-height: 36rpx;
	// }

	.book-style {
		color: #2440b3;
		font-size: 24rpx;
		line-height: 36rpx;

	}

	.cell-info {
		width: 100%;
		padding: 10rpx 0;
		margin-top: 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		input {
			width: 100%;
		}

		text {
			margin-right: 30rpx;
			flex-shrink: 0;
		}
	}

	.avatar-wrapper {
		width: 100%;
		height: 200rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		image {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
		}
	}

	.showInfo-view {
		width: 600rpx;
		height: 600rpx;
		background-color: #fff;
	}

	.popup-view {
		width: 600rpx;
		height: 600rpx;
		background-color: #ffffff;
		border-radius: 20rpx;
		overflow: hidden;
		padding: 50rpx 0;
		box-sizing: border-box;

		.popup-view-title {
			height: 100rpx;
			text-align: center;
			line-height: 100rpx;
			font-size: 28rpx;
			color: #222;
		}

		.cell-list {
			display: flex;
			align-items: center;
			margin-top: 30rpx;
			width: 500rpx;
			margin-left: 50rpx;

			// padding: 20rpx 0;
			&-left {
				width: 160rpx;
				flex-shrink: 0;
			}

			.refreshIcon {
				width: 100rpx;
				height: 100rpx;
				border-radius: 50%;
				overflow: hidden;
			}

			.right-pic {

				button {
					background-color: #ffffff;
					width: 120rpx;
					height: 120rpx;
					padding: 0;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				button::after {
					border: none;
				}
			}
		}

		.btn1 {
			margin-top: 60rpx;

			.btn-sub {
				width: 500rpx;
				background-color: #3643bd;
				height: 80rpx;
				color: #fff;
				border-radius: 15rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-left: 50rpx;
			}
		}
	}
	.h5-biaodan-new{
		display: flex;
		flex-direction: column;
		align-items: center;
		.h5-biaodan-new-img{
			width: 200rpx;
			height: 200rpx;
			image{
				width: 100%;
				height: 100%;
			}
		}
		&-label{
			font-size: 22rpx;
			margin-top: 30rpx;
		}
		&-btn{
			width: 600rpx;
			height: 80rpx;
			background-color: #222;
			color: #ffffff;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 44rpx;
		}
		&-tip{
			margin-top: 24rpx;
			font-size: 20rpx;
			color: #8a8a8a;
		}
	}
</style>